package com.qqt.csr.common.utils;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZip工具类
 * zip压缩解压并使用Base64进行编码工具类
 */
@Slf4j
public class GzipUtil {
    /**
     * 将字符串进行gzip压缩
     *
     * @param data
     * @return
     */
    public static String compress(String data) {
        if (StringUtils.isBlank(data)) {
            return StringUtils.EMPTY;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(data.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            log.error("压缩异常，data:{}", data, e);
        }
        return Base64.getEncoder().withoutPadding().encodeToString(out.toByteArray());
    }

    /**
     * 解压字符串
     *
     * @param data
     * @return
     */
    public static String unCompress(String data) {
        if (StringUtils.isBlank(data)) {
            return StringUtils.EMPTY;
        }
        byte[] decode = Base64.getDecoder().decode(data);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(decode);
        try (GZIPInputStream gzipStream = new GZIPInputStream(in)) {
            byte[] buffer = new byte[256];
            int n;
            while ((n = gzipStream.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("解压异常，data：{}", data, e);
        }
        return data;
    }
}
